﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using Android.App;
using Android.OS;
using Android.Util;
using Android.Views;
using Java.Net;
using Newtonsoft.Json;
using File = Java.IO.File;

namespace MapDrawer
{
    [Activity(Label = "SIG")]
    public class MainActivity : Activity
    {
        #region constants

        private string filename;
        #endregion

        #region fields
        // A reference to the painter view
        private Painter _painter = null;

        // Gesture management
        private Android.Views.ScaleGestureDetector _scaleGestureDetector;
        private float[] _initialCoordinates;
        private Trip _trip;
	    private JsonOsm _jsonOsm;

        #endregion
        #region properties
        // The trip to draw
        public Trip Trip
        {
            get
            {
                if (_trip == null)
                    InitArrays();
                return _trip;
            }
            private set { _trip = value; }
        }
        
	    public JsonOsm Osm
	    {
		    get
		    {
			    if (_jsonOsm == null)
			    {
				    InitArrays();
			    }
			    return _jsonOsm;
		    }
	    }

        public bool TripAvailable
        {
            get
            {
                return _trip != null;
            }
        }

        #endregion
       
        /// <summary>
        /// If arrays are cached, loads them from the cache.
        /// If not, arrays are parsed from the xml file.
        /// The trip is loaded from the file each time.
        /// </summary>
        private void InitArrays()
        {
	        string content = "";
	        using (Stream stream = Resources.Assets.Open("osm.json"))
	        {
		        using (MemoryStream output = new MemoryStream())
		        {
			        stream.CopyTo(output);
			        content = Encoding.UTF8.GetString(output.ToArray());
		        }
	        }
			

	        _jsonOsm = JsonConvert.DeserializeObject<JsonOsm>(content, new JsonSerializerSettings()
	        {
		        PreserveReferencesHandling = PreserveReferencesHandling.None
	        });


            // Get trip
            if (filename != null)
            {
                Trip = new Trip(filename);
                Trip.Points.ForEach(
                    point =>
                        point.Coordinates.TranslateOnMap(_jsonOsm.MinLat, _jsonOsm.MinLon, _jsonOsm.MaxLat,
                            _jsonOsm.MaxLon));
            }
        }
        #region android methods
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            string directoryName = "/storage/sdcard0/";
            string file = Intent.GetStringExtra("file");
            if (file != null)
                filename = "/storage/sdcard0/" + file;
            else
                filename = null;
            
            InitArrays();
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            // Scale Gesture
            _scaleGestureDetector = new Android.Views.ScaleGestureDetector(this, new ScaleGestureDetector(_painter));
        }

        public override bool OnTouchEvent(MotionEvent e)
        {
            _scaleGestureDetector.OnTouchEvent(e);
            switch (e.Action)
            {
                case MotionEventActions.Down:
                    _initialCoordinates = new float[2];
                    _initialCoordinates[0] = e.GetX();
                    _initialCoordinates[1] = e.GetY();
                    break;
                case MotionEventActions.Move:
                    if (_initialCoordinates != null)
                    {
                        var x = (e.GetX() - _initialCoordinates[0])/1000;
                        var y = (e.GetY() - _initialCoordinates[1])/1000;
                        _initialCoordinates[0] = e.GetX();
                        _initialCoordinates[1] = e.GetY();
                        Log.Debug("TouchEventMoveHandler", "Moving: values(" + x + ", " + y + ")");
                        _painter.MoveMap(x, -y);
                    }
                    break;
                case MotionEventActions.Up:
                    _initialCoordinates = null;
                    break;
            }
            return base.OnTouchEvent(e);
        }
        #endregion
        public void RegisterPainter(Painter p)
        {
            this._painter = p;
        }
    }
}

